package offer;

public class Solution29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int up = 0, down = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        int length = (down + 1) * (right + 1);
        int[] res = new int[length];
        int index = 0;
        while (index < length) {
            for (int i = left; i <= right; i++) {
                res[index++] = matrix[up][i];
            }
            up++;
            if (index == length) {
                break;
            }
            for (int i = up; i <= down; i++) {
                res[index++] = matrix[i][right];
            }
            right--;
            if (index == length) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res[index++] = matrix[down][i];
            }
            down--;
            if (index == length) {
                break;
            }
            for (int i = down; i >= up; i--) {
                res[index++] = matrix[i][left];
            }
            left++;
        }
        return res;
    }
}
